package com.example.myys.network

import android.annotation.SuppressLint
import android.webkit.WebView
import com.example.myys.Constants.Companion.UserAgent
import com.example.myys.MyApplication
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import okhttp3.Cache
import okhttp3.Dns
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.Inet4Address
import java.net.InetAddress
import java.nio.charset.Charset
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.X509TrustManager

// 自定义DNS解析器，优先返回IPv4地址
class CustomDns : Dns {
    override fun lookup(hostname: String): List<InetAddress> {
        val addresses = InetAddress.getAllByName(hostname)
        val filteredAddresses = mutableListOf<InetAddress>()
        for (address in addresses) {
            if (address is Inet4Address) {
                filteredAddresses.add(0, address)
            } else {
                //filteredAddresses.add(address)
            }
        }
        return filteredAddresses
    }
}
//okhhtp连接
object HttpClient {
    var client: OkHttpClient? = null

    init {
        //ssl配置
        val trustManager = object : X509TrustManager {
            override fun checkClientTrusted(
                chain: Array<out X509Certificate>,
                authType: String
            ) {
            }

            override fun checkServerTrusted(
                chain: Array<out X509Certificate>,
                authType: String
            ) {
            }

            override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
        }
        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, arrayOf(trustManager), SecureRandom())

        val sslSocketFactory = sslContext.socketFactory
        val hostnameVerifier = HostnameVerifier { _, _ -> true }

        //缓存配置
        val cache: Cache =
            Cache(MyApplication.instance.getCacheDir(), 40 * 1024 * 1024) // 40 MB cache
        client = OkHttpClient().newBuilder()
            .followRedirects(false)
            .cache(cache)
            .sslSocketFactory(
                sslSocketFactory,
                trustManager
            ) // //通过sslSocketFactory方法设置https证书
            .hostnameVerifier(hostnameVerifier)
            .dns(CustomDns())
            .connectTimeout(10L, TimeUnit.SECONDS)
            .readTimeout(20L, TimeUnit.SECONDS)
            .writeTimeout(20L, TimeUnit.SECONDS)
            .build()
    }

    /**
     * 请求
     */
    fun get(url: String, head: Map<String, String> = mapOf(), ecode: String = "utf-8"): String? {
        //清除旧的请求
        val dispatcher = client?.dispatcher
        if (dispatcher != null) {
            for (call in dispatcher.queuedCalls()!!) {
                call.cancel()
            }
        }
        val requestBuilder = Request.Builder()
            .header("User-Agent", UserAgent)
        for (hd in head) {
            requestBuilder.addHeader(hd.key, hd.value)
        }
        val request = requestBuilder.url(url)
            .build()
        try {
            val response = client?.newCall(request)?.execute()
            if (response != null) {
                if (response.isSuccessful) {
                    if (ecode.equals("gbk")) {
                        return response.body?.bytes()?.toString(Charset.forName("GBK"))
                    }
                    return response.body?.string()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 请求
     */
    fun post(
        url: String,
        head: Map<String, String> = mapOf(),
        body: Map<String, String> = mapOf()
    ): String? {
        //清除旧的请求
        val dispatcher = client?.dispatcher
        if (dispatcher != null) {
            for (call in dispatcher.queuedCalls()) {
                call.cancel()
            }
        }
        val requestBuilder = Request.Builder()
            .header("User-Agent", UserAgent)
        for (hd in head) {
            requestBuilder.addHeader(hd.key, hd.value)
        }
        val formBodyBuilder = FormBody.Builder()
        for (bd in body) {
            formBodyBuilder.add(bd.key, bd.value)
        }
        val request = requestBuilder.url(url)
            .post(formBodyBuilder.build())
            .build()
        try {
            val response = client?.newCall(request)?.execute()
            if (response != null) {
                if (response.isSuccessful) {
                    return response.body?.string()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    //通过webview获取页面
    @SuppressLint("SuspiciousIndentation")
    suspend fun getWebviewUrl(url: String, jsString: String): String {
        val deferredResult = CompletableDeferred<String>()
            withContext(Dispatchers.Main) {
                val webView = WebView(MyApplication.instance)
                // Initialize and load the WebView in a coroutine
                webView.settings.javaScriptEnabled = true
                webView.settings.domStorageEnabled = true
                webView.loadUrl(url)

                delay(10000)
                webView?.evaluateJavascript("(function(){return document.documentElement.outerHTML;})()") { html ->
                    // 在这里处理获取到的HTML内容
                    //println(html)
                    deferredResult.complete(html)
                }
            }
        return deferredResult.await()
    }
}